//
//  KAPictureVerifyView.swift
//  kano
//
//  Created by Frank on 2024/8/29.
//

import UIKit
import Kingfisher
import RxCocoa
import RxSwift

class KAPictureVerifyView: UIView, UITextViewDelegate {
    
    private var keyBoardHeight: CGFloat = 0.0
    
    private lazy var backgroundView: UIVisualEffectView = {
        let blurEffect = UIBlurEffect(style: .light)
        let var_backgroundView = UIVisualEffectView(frame: bounds)
        var_backgroundView.effect = blurEffect
        
        var_backgroundView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        var_backgroundView.frame = self.bounds
        let tap = UITapGestureRecognizer(target: self, action: #selector(dismiss))
        var_backgroundView.addGestureRecognizer(tap)
        return var_backgroundView
    }()
    
    private lazy var shadowView: UIView = {
        let view = UIView()
        view.layer.masksToBounds = false
        view.layer.shadowOffset = CGSize(width: 0, height: 0)
        view.layer.shadowRadius = 23
        view.layer.shadowOpacity = 1
        view.layer.shadowColor = UIColor.black.withAlphaComponent(0.1).cgColor
        view.frame = CGRect(x: 0, y: var_screenHeight - 254, width: var_screenWidth, height: 254)
        return view
    }()
    
    private lazy var contentView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.layer.mask = CAShapeLayer()
        return view
    }()
    
    private lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 18, weight: .medium)
        label.textColor = .black
        label.text = "Enter the graphic verification code"
        return label
    }()
    
    private lazy var closeButton: UIButton = {
        let button = UIButton(type: .custom)
        button.addTarget(self, action: #selector(closeAction(_:)), for: .touchUpInside)
        button.setImage(UIImage(named: "text_clear"), for: .normal)
        return button
    }()
    
    private lazy var verifyImageV: UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "home_numCollect")
        imageView.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(generatePic))
        imageView.addGestureRecognizer(tap)
        return imageView
    }()
    
    private lazy var tipLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 1
        label.textAlignment = .center
        label.textColor = .color77777D
        label.font = UIFont.systemFont(ofSize: 13)
        label.text = "Click on the picture to refresh"
        return label
    }()
    
    
    private var captcheId: String = ""
    
    private var complete: ((String, String) -> Void)?
    
    private var autoDismiss: Bool = false
    
    private lazy var msgCodeView: KAAuthView = {
        let view = KAAuthView(count: 4, margin: kscale(12.5), handler: { [self] code in
            if code.count == 4 && complete != nil {
                complete!(code, captcheId)
                if autoDismiss {
                    dismiss()
                }
            }
        })
        view.textField.keyboardType = .namePhonePad
        return view
    }()
    
    init(complete: @escaping (_ code:String, _ captcheId:String) -> Void) {
        self.complete = complete
        super.init(frame: UIScreen.main.bounds)
        setupSubViews()
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
        NotificationCenter.default.removeObserver(self, name: UITextView.textDidChangeNotification, object: nil)
    }
    
    @objc private func generatePic() {
        showLoading()
        loginProvider.request(.picVerify()) { result in
            self.hideLoading()
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KAContent>.handleResponseData(response.data) { isSuccess, message, response in
                        if isSuccess {
                            guard let content = response?.voucherQuantity else { return }
                            self.captcheId = content.creditComponent
                            self.verifyImageV.kf.setImage(with: URL(string: NetConfig.fullImgUrl(path: self.captcheId)))
                        } else {
                            self.makeToast(message)
                        }
                    }
                }else {
                    self.makeToast(badNetWorking)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
    
    private func setupSubViews() {

        addSubview(backgroundView)
        addSubview(shadowView)
        
        contentView.frame = shadowView.bounds
        shadowView.addSubview(contentView)
        
        let maskPath = UIBezierPath(roundedRect: contentView.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 13, height: 13))
        let maskLayer = CAShapeLayer()
        maskLayer.frame = contentView.bounds
        maskLayer.path = maskPath.cgPath
        contentView.layer.mask = maskLayer
        
        contentView.addSubview(titleLabel)
        contentView.addSubview(closeButton)
        contentView.addSubview(verifyImageV)
        contentView.addSubview(tipLabel)
        contentView.addSubview(msgCodeView)
        
        closeButton.translatesAutoresizingMaskIntoConstraints = false
        titleLabel.translatesAutoresizingMaskIntoConstraints = false
        verifyImageV.translatesAutoresizingMaskIntoConstraints = false
        tipLabel.translatesAutoresizingMaskIntoConstraints = false
        msgCodeView.translatesAutoresizingMaskIntoConstraints = false
        
        NSLayoutConstraint.activate([
            closeButton.widthAnchor.constraint(equalToConstant: 40),
            closeButton.heightAnchor.constraint(equalToConstant: 40),
            closeButton.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 6.5),
            closeButton.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -6.5),
            
            titleLabel.centerXAnchor.constraint(equalTo: contentView.centerXAnchor),
            titleLabel.centerYAnchor.constraint(equalTo: closeButton.centerYAnchor),
            
            verifyImageV.widthAnchor.constraint(equalToConstant: kscale(143)),
            verifyImageV.heightAnchor.constraint(equalToConstant: kscale(52)),
            verifyImageV.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: kscale(30)),
            verifyImageV.centerXAnchor.constraint(equalTo: contentView.centerXAnchor),
            
            tipLabel.topAnchor.constraint(equalTo: verifyImageV.bottomAnchor, constant: kscale(8)),
            tipLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
            tipLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
            
            msgCodeView.topAnchor.constraint(equalTo: tipLabel.bottomAnchor, constant: kscale(20)),
            msgCodeView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: kscale(86)),
            msgCodeView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -kscale(86)),
            msgCodeView.heightAnchor.constraint(equalToConstant: 50)
        ])
        
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHidden(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)

    }
    
    @objc func keyboardWillShow(_ notification: Notification) {
        guard let userInfo = notification.userInfo, let keyBoardRect = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else {
            return
        }
        keyBoardHeight = keyBoardRect.height
        UIView.animate(withDuration: userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval ?? 0, animations: {
            self.shadowView.transform = CGAffineTransform(translationX: 0, y: -self.keyBoardHeight)
        })
    }
    
    @objc func keyboardWillHidden(_ notification: Notification) {
        UIView.animate(withDuration: notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval ?? 0, animations: {
            self.shadowView.transform = .identity
        })
    }
    
    func show() {
        generatePic()
        msgCodeView.clearContent()
        guard let rootWindow = UIApplication.shared.windows.first(where: { $0.isKeyWindow }) else { return }
        rootWindow.addSubview(self)
        msgCodeView.becomeFirstResponder()
        backgroundView.alpha = 0
        UIView.animate(withDuration: 0.25, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 1, options: .curveLinear, animations: {
            self.backgroundView.alpha = 1
            self.alpha = 1
        }, completion: nil)
    }
    
    @objc func dismiss() {
        msgCodeView.clearContent()
        endEditing(true)
        UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 1, options: .curveLinear, animations: {
            self.alpha = 0
        }, completion: { _ in
            self.removeFromSuperview()
        })
    }
    
    @objc private func closeAction(_ sender: UIButton) {
        dismiss()
    }
}
